import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Select, Button, Input, Table, Badge, message, Popover } from 'antd'
import approveSuggestService from 'containers/setting/approve-suggest/approve-suggest.service'
import 'styles/finance-setting/audit-opinion/audit-opinion.scss'
import debounce from 'lodash.debounce'
import NewApproveSuggest from 'containers/setting/approve-suggest/new-approve-suggest'
import SlideFrame from  'components/slide-frame'
const Option = Select.Option;
const Search = Input.Search;
import ResizeTable from "components/resize-table";

class ApproveSuggest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      onLoad: false,
      offLoad: false,
      columns: [
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: 'index',
          render: (value, record, index) => this.state.size * this.state.page + index + 1
        },
        {
          title: messages('setting.key1224')/*编码*/,
          dataIndex: 'code',
          render: value => <Popover content={value} placement='topLeft'>{value}</Popover>
        },
        {
          title: messages('setting.key1378')/*审批意见*/,
          dataIndex: 'reply',
          width: '70%',
          render: value => <Popover content={value} placement='topLeft'>{value}</Popover>
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'status',
          render: value => {
            return value === 1000 ? <Badge text={messages('common.status.enable')/*启用*/} status={'success'}/> :
              <Badge text={messages('common.status.disable')/*禁用*/} status={'error'}/>
          }
        }
      ],
      data: [],
      tableLoading: false,
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectedDataIds: [],
      searchValue: '',
      slideShow: false
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount() {
    this.handleChangeKey();
  };

  //选择项改变触发事件
  onSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  //点击选择
  onSelectItem = (record, selected) => {
    let { selectedDataIds, rowSelection } = this.state;
    if (!selected) {
      selectedDataIds.map((select, index) => {
        if (select.id === record.id) {
          selectedDataIds.splice(index, 1);
        }
      })
    } else {
      selectedDataIds.push(record);
    }
    this.setState({ selectedDataIds, rowSelection: rowSelection });
  };

  //全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    let { selectedDataIds } = this.state;
    if (!selected) {
      changeRows.map(record => {
        selectedDataIds.map((select, index) => {
          if (select.id === record.id) {
            selectedDataIds.splice(index, 1);
          }
        })
      });
    } else {
      selectedRows.map(item => {
        let isContainer = false;
        selectedDataIds.map(select => {
          if (select.id === item.id) {
            isContainer = true;
          }
        });
        !isContainer && (selectedDataIds.push(item));
      });
    }
    this.setState({ selectedDataIds });
  };


  //新建审核意见
  newOpinion = () => {
    this.setState({ slideShow: true });
  };

  //启用/禁用审核意见
  handleOnOrOff = (e) => {
    const { selectedDataIds } = this.state;
    let ids = [];
    selectedDataIds.map(item => {
      ids.push(item.id);
    });
    let params = {
      ids: ids,
      statusEnum: e === 'on' ? 'USING' : 'DELETED'
    };
    approveSuggestService.onOrOffReply(params).then(() => {
      this.handleChangeKey();
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/));
    })
  };

  //搜索
  handleChangeKey = (e) => {
    let value = e ? e.target.value : this.state.searchValue;
    const { page, size } = this.state;
    this.setState({ page: 0 });
    this.setState({ tableLoading: true, searchValue: value });
    let params = {
      page: 0,
      size,
      tenantId: this.props.user.tenantId,
      searchParam: value
    };
    this.handleSearch(params);
  };

  handleSearch = (params) => {
    const { page } = this.state;
    approveSuggestService.getReplyList(params).then(res => {
      this.setState({
        data: res.data.rows,
        tableLoading: false,
        pagination: {
          total: res.data.total,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/))
    });
  };

  //分页
  onChangePager = (page) => {
    const { size, searchParam } = this.state;

    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        tableLoading: true,
      }, () => {
        let params = {
          size,
          tenantId: this.props.user.tenantId,
          page: page - 1,
          searchParam
        };
        this.handleSearch(params);
      })
  };

  render() {
    const { onLoad, offLoad, columns, data, pagination, tableLoading, rowSelection, slideShow, selectedDataIds } = this.state;
    const { tenantMode } =this.props;
    return (
      <div className="audit-opinion">
        <div className="audit-opinion-operate">
          {tenantMode && <Button type='primary' size='large' onClick={this.newOpinion}
                                 disabled={!this.props.tenantMode}>{messages('setting.key1513')/*新建审批意见*/}</Button>}
          <Button onClick={() => this.handleOnOrOff('on')} loading={onLoad} style={{ marginLeft: '20px' }}
                  disabled={!this.props.tenantMode || !(selectedDataIds.length > 0)}>{messages('common.status.enable')/*启用*/}</Button>
          <Button onClick={() => this.handleOnOrOff('off')} loading={offLoad} style={{ marginLeft: '10px' }}
                  disabled={!this.props.tenantMode || !(selectedDataIds.length > 0)}>{messages('common.status.disable')/*禁用*/}</Button>
          <Search onChange={this.handleChangeKey}
                  style={{ display: 'block', float: 'right', width: '400px', top: '50%', marginTop: '-16px' }}
                  maxLength={100}
                  placeholder={messages('setting.key1514')/*请输入审批意见*/}/>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          rowKey='code'
          bordered
          size={'middle'}
          rowSelection={rowSelection}
          pagination={pagination}
          loading={tableLoading}
        />
        <SlideFrame show={slideShow}
                    title={messages('setting.key1378')/*审批意见*/}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      slideShow,
                    }}
                    content={NewApproveSuggest}
                    onClose={(isRefresh) => {
                      this.setState({ slideShow: false });
                      isRefresh === true && this.handleChangeKey();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({ slideShow: false });
                      isRefresh === true && this.handleChangeKey();
                    }}/>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(ApproveSuggest);
